/**
 * Copyright @ 2000 ysten Co. Ltd. 
 * All right reserved.     
 * @author: wangmin
 * date: 2016-07-11     
 */
package com.task.service.impl;

import com.task.bean.Constants;
import com.task.bean.EnumConstants;
import com.task.bean.EnumConstants.ChildTaskStatus;
import com.task.entity.ChildTask;
import com.task.entity.ParentTask;
import com.task.entity.User;
import com.task.repository.IChildTaskRepository;
import com.task.repository.IParentTaskRepository;
import com.task.repository.IUserRepository;
import com.task.service.IChildTaskService;
import com.task.service.IRedPackageService;
import com.task.utils.DateTimeUtils;
import com.task.utils.PageUtil;
import com.task.utils.PropertiesUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 子任务服务
 */
@Service
public class ChildTaskServiceImpl implements IChildTaskService {
    public static final String YYYY_M_MDD = "yyyyMMdd";

    //是否发送红包标记（0：不发送，1:发送）
    public static final String RED_PACKAGE_FLAG = "redPackageFlag";

    @Autowired
    IChildTaskRepository childTaskRepository;

    @Autowired
    IParentTaskRepository parentTaskRepository;

    @Autowired
    IUserRepository userRepository;

    @Autowired
    IRedPackageService redPackageService;

    @Override
    public Page<ChildTask> findTaskList(Map<String, Object> searchParams, int pageNum, int rows) {
        PageRequest pageRequest = PageUtil.buildPageRequest(pageNum, rows, Constants.DESC, Constants.ID);
        Specification<ChildTask> spec = PageUtil.buildSpecification(searchParams, ChildTask.class);
        return childTaskRepository.findAll(spec, pageRequest);
    }

    @Override
    public ChildTask findById(Long id) {
        return childTaskRepository.findOne(id);
    }

    @Override
    public void save(ChildTask childTask) {
        childTask.setCode(getChildTaskCode(childTask));
        childTaskRepository.save(childTask);
    }

    @Override
    public void update(ChildTask childTask) {
        childTaskRepository.save(childTask);
    }


    @Override
    public String getChildTaskCode(ChildTask task) {
        String parentTaskCode = task.getParentTask().getCode();
        String separator = "-";
        String childCode = task.getChildTaskCode();
        while (childCode.length() < 4) {
            childCode = "0" + childCode;
        }
        return parentTaskCode + separator + childCode;
    }

    @Override
    public List<ChildTask> findByCondition(Map<String, Object> searchParams) {
        Specification<ChildTask> spec = PageUtil.buildSpecification(searchParams, ChildTask.class);
        return childTaskRepository.findAll(spec);
    }

    @Override
    public Integer getCountByParentTaskId(Long parentTaskId) {
        return childTaskRepository.getCountByParentTaskId(parentTaskId);
    }

    @Override
    public void delByParentTaskId(Long id) {
        childTaskRepository.deleteByParentTaskId(id);
    }

    @Override
    public void updateStatus(ChildTaskStatus status, Long id) {
        ChildTask task = childTaskRepository.findOne(id);
        if (null != task) {
            task.setStatus(status);
            childTaskRepository.save(task);
        }
    }

    @Override
    public void updateWhileCheck(ChildTaskStatus status, Long id) {
        boolean isFinish = true;
        boolean isClose = true;
        ChildTask child = childTaskRepository.findOne(id);
        ParentTask pt = parentTaskRepository.findOne(child.getParentTaskId());
        Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("EQ_parentTaskId", child.getParentTaskId());
        List<ChildTask> ctList = findByCondition(searchParams);
        for (ChildTask ct : ctList) {
            if (ct.getStatus().equals(ChildTaskStatus.SAVE) || ct.getStatus().equals(ChildTaskStatus.PUBLISH)
                    || ct.getStatus().equals(ChildTaskStatus.DOING)
                    || ct.getStatus().equals(ChildTaskStatus.SUBMIT)) {
                isFinish = false;
                isClose = false;
                break;
            } else if (isClose && !ct.getStatus().equals(ChildTaskStatus.CLOSE)) {
                isClose = false;
            }
        }

        if (isFinish) {
            if (isClose) {
                pt.setStatus(EnumConstants.ParentTaskStatus.CLOSE);
            } else {
                pt.setStatus(EnumConstants.ParentTaskStatus.END);
            }
            parentTaskRepository.save(pt);
        }

        if (null != child) {
            child.setStatus(status);
            child.setFinishTime(new Date());
            childTaskRepository.save(child);

            if (status == ChildTaskStatus.PASS) {//审核通过，发送红包

                 /*发送红包 start*/
                User user = userRepository.findByUserId(child.getUserId());
                String sendRedPackageFlag = PropertiesUtil.getProperty(RED_PACKAGE_FLAG);
                boolean sendRedResult = false;
                if (StringUtils.equals(sendRedPackageFlag, "1")) {//发送红包
                    if (user != null && child != null && child.getReward() != null) {
                        String openId = user.getOpenId();
                        Float reward = child.getReward();
                        if (StringUtils.isNotBlank(openId) && reward != null) {
                            sendRedResult = redPackageService.sendPackage(openId, (int) (reward * 100));
                        }
                    }
                }

                if (sendRedResult) {//红包发送成功，更新账户总额
                    Float cumulativeReward = user.getCumulativeReward();
                    if (cumulativeReward != null) {
                        user.setCumulativeReward(cumulativeReward + child.getReward());
                    } else {
                        user.setCumulativeReward(child.getReward());
                    }
                    userRepository.save(user);
                }
                /*发送红包 end*/

                //TODO 模拟用户账户奖金增加，等到红包商户开通成功后，请注释或删除该段代码，start
                Float cumulativeReward = user.getCumulativeReward();
                if (cumulativeReward != null) {
                    user.setCumulativeReward(cumulativeReward + child.getReward());
                } else {
                    user.setCumulativeReward(child.getReward());
                }
                userRepository.save(user);
                //TODO end
            }
        }
    }

    @Override
    public Page<ChildTask> findChildList(Map<String, Object> searchParams, int pageNum, int rows, String orderDirection,
                                         String orderField) {

        //增加日期过滤，过期的任务消失
        String nowDate = DateTimeUtils.formatDateToString(new Date());
        searchParams.put("LTE_parentTask.startTime", nowDate);
        searchParams.put("GTE_parentTask.endTime", nowDate);
        PageRequest pageRequest = PageUtil.buildPageRequest(pageNum, rows, orderDirection, orderField);
        Specification<ChildTask> spec = PageUtil.buildSpecification(searchParams, ChildTask.class);
        return childTaskRepository.findAll(spec, pageRequest);
    }

    @Override
    public Page<ChildTask> findMyTaskList(Map<String, Object> searchParams, int pageNum, int rows, String orderDirection, String orderField) {
        PageRequest pageRequest = PageUtil.buildPageRequest(pageNum, rows, orderDirection, orderField);
        Specification<ChildTask> spec = PageUtil.buildSpecification(searchParams, ChildTask.class);
        return childTaskRepository.findAll(spec, pageRequest);
    }
}
